package pers.zw.study.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

@WebServlet(name = "ServletCookieDemo1",urlPatterns = "/ServletCookieDemo1")
public class ServletCookieDemo1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");

        response.setContentType("text/html; charset = UTF-8");
        PrintWriter out = response.getWriter();

        Cookie[] cookies = request.getCookies();

        if (cookies != null) {
            out.write("上次访问的时间是：");
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("lastAccessTime")) {
                    long lastAccessTime = Long.parseLong(cookie.getValue());
                    Date date = new Date(lastAccessTime);
                    out.write(date.toString());
                }
            }
        } else {
            out.write("第一次访问本站！");
        }

        //访问之后更新访问时间
        Cookie cookie = new Cookie("lastAccessTime", System.currentTimeMillis() + "");

        response.addCookie(cookie);
    }
}
